﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Team4Mock.Entity;


namespace Team4Mock.UserControl.Service
{
    public partial class ViewAll : System.Web.UI.UserControl
    {
        ServiceEntity se = new ServiceEntity();
        PremiseEntity pe = new PremiseEntity();
        ContractEntities ce = new ContractEntities();
        FundingEntities fe = new FundingEntities();
        ServicePremiseEntities sp = new ServicePremiseEntities();
        AEntities ae=new AEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    pnAmend.Visible = true;
                    pnView.Visible = false;
                    pnAdd.Visible = false;
                    gvOrg.DataSource = se.GetOrg();
                    gvOrg.DataBind();
                    dlProgram.DataSource = se.GetProgram();
                    dlProgram.DataBind();

                    int id = int.Parse(Request.QueryString["ID"]);
                    sp.SerId = id;
                    gvPremise.DataSource = sp.GetServicePremise(sp);
                    gvPremise.DataBind();
                    GridView1.DataSource = sp.SerPre_GetPre(sp);
                    GridView1.DataBind();

                    se.ServiceID = id;
                    DataTable dt = new DataTable();
                    dt = se.GetdataByID(se);
                    txtSerName.Text = dt.Rows[0][1].ToString();
                    txtShortDes.Text = dt.Rows[0][2].ToString();
                    hdContact.Value = dt.Rows[0][4].ToString();
                    dlServiceSubType.SelectedValue = dt.Rows[0][3].ToString();
                    if (dt.Rows[0][3].ToString().Equals("Contract"))
                    {
                        ce.ServiceID = id;
                        lbdiv.Text = "<li><a href=\"#Contract\" class=\"tab\">Contract</a></li>";
                        GetCheckboxList(se.GetRef("Ser_GetContractObli"), se.GetRefByID(id, "Ser_GetContractObliByID"), clContractObligation);
                        GetCheckboxList(se.GetRef("Ser_GetContractOutCome"), se.GetRefByID(id, "Ser_GetContractOutComeByID"), clContractOutCome);
                        DataTable dt2 = new DataTable();
                        dt2 = ce.Getdata(ce);
                        dlParticipation.SelectedValue = dt2.Rows[0][2].ToString();

                    }
                    if (dt.Rows[0][3].ToString().Equals("Funding"))
                    {
                        lbdiv.Text = "<li><a href=\"#Funding\" class=\"tab\">Funding</a></li>";
                        fe.ServiceID = id;
                        DataTable dt1 = new DataTable();
                        dt1 = fe.GetFunding(fe);
                        dlFundingSource.SelectedValue = dt1.Rows[0][2].ToString();
                        idMediaContact.Value = dt1.Rows[0][3].ToString();
                        txtFunAmount.Text = dt1.Rows[0][4].ToString();
                        txtFunStart.Text = dt1.Rows[0][5].ToString();
                        txtFunEnd.Text = dt1.Rows[0][6].ToString();
                        txtFundaisingText.Text = dt1.Rows[0][7].ToString();
                        txtFundaisingWhy.Text = dt1.Rows[0][8].ToString();
                        ckFundaisingDonorAnon.Checked = dt1.Rows[0][9].ToString().Equals("1") ? true : false;
                        txtFundaisingDonoAmount.Text = dt1.Rows[0][10].ToString();
                        txtFunNeeds.Text = dt1.Rows[0][11].ToString();
                        ckFunContiNeed.Checked = dt1.Rows[0][12].ToString().Equals("1") ? true : false;
                        txtFunContiAmount.Text = dt1.Rows[0][13].ToString();
                        txtFunConDetails.Text = dt1.Rows[0][14].ToString();
                        txtFundaisingNeed.Text = dt1.Rows[0][15].ToString();
                        txtFundaisingRequiBy.Text = dt1.Rows[0][16].ToString();
                        ckFundaisingComplete.Checked = dt1.Rows[0][17].ToString().Equals("1") ? true : false;
                        txtFundaisingCompleDate.Text = dt1.Rows[0][18].ToString();
                        txtFundaisingDonationDate.Text = dt1.Rows[0][19].ToString();
                        ckFundaisingDonaIncrement.Checked = dt1.Rows[0][20].ToString().Equals("1") ? true : false;

                    }
                    txtClientDes.Text = dt.Rows[0][5].ToString();
                    dlAttendannce.SelectedValue = dt.Rows[0][6].ToString();
                    txtStartExp.Text = dt.Rows[0][7].ToString();
                    txtStartDate.Text = dt.Rows[0][8].ToString();
                    txtEndDate.Text = dt.Rows[0][9].ToString();
                    ckExtandable.Checked = dt.Rows[0][10].ToString().Equals("1") ? true : false;
                    txtExtenYear.Text = dt.Rows[0][11].ToString();
                    txtExtenMonth.Text = dt.Rows[0][12].ToString();
                    ckActive.Checked = dt.Rows[0][25].ToString().Equals("1") ? true : false;
                    txtDesFull.Text = dt.Rows[0][13].ToString();
                    txtDeptCode.Text = dt.Rows[0][14].ToString();
                    dlSerType.SelectedValue = dt.Rows[0][15].ToString();
                    txtDesDelivery.Text = dt.Rows[0][16].ToString();
                    txtContactCode.Text = dt.Rows[0][17].ToString();
                    txtContactValue.Text = dt.Rows[0][18].ToString();
                    ckStagedPayment.Checked = dt.Rows[0][19].ToString().Equals("1") ? true : false;
                    dlProcessMethod.SelectedValue = dt.Rows[0][20].ToString();
                    ckTimeLimited.Checked = dt.Rows[0][21].ToString().Equals("1") ? true : false;
                    txtLimitedYear.Text = dt.Rows[0][22].ToString();
                    txtLimitedMonth.Text = dt.Rows[0][23].ToString();
                    dlProgram.SelectedValue = dt.Rows[0][24].ToString();

                    GetCheckboxList(se.GetRef("Ser_GetAcc"), se.GetRefByID(id, "Ser_GetAccByID"), clClientAcc);
                    GetCheckboxList(se.GetRef("Ser_GetBarCri"), se.GetRefByID(id, "Ser_GetBarCriByID"), clBarriers);
                    GetCheckboxList(se.GetRef("Ser_GetBenCri"), se.GetRefByID(id, "Ser_GetBenCriByID"), clBenefit);
                    GetCheckboxList(se.GetRef("Ser_GetClientJourney"), se.GetRefByID(id, "Ser_GetClientJourneyByID"), clClientJourrey);
                    GetCheckboxList(se.GetRef("Ser_GetClientOutCome"), se.GetRefByID(id, "Ser_GetClientOutComeByID"), clClientOutCome);
                    GetCheckboxList(se.GetRef("Ser_GetClientSupPro"), se.GetRefByID(id, "Ser_GetClientSupProByID"), clSupportProcess);
                    GetCheckboxList(se.GetRef("Ser_GetDisCri"), se.GetRefByID(id, "Ser_GetDisCriByID"), clDisability);
                    GetCheckboxList(se.GetRef("Ser_GetEthCri"), se.GetRefByID(id, "Ser_GetEthCriByID"), clEthnic);
                    GetCheckboxList(se.GetRef("Ser_GetIntervention"), se.GetRefByID(id, "Ser_GetInterventionByID"), clIntervention);
                    GetCheckboxList(se.GetRef("Ser_GetOthSer"), se.GetRefByID(id, "Ser_GetOtherServiceByID"), clOtherService);
                    GetCheckboxList(se.GetRef("Ser_GetPerCirCri"), se.GetRefByID(id, "Ser_GetPerCirCriByID"), clPersonalCri);
                    GetCheckboxList(se.GetRef("Ser_GetRefSou"), se.GetRefByID(id, "Ser_GetRefSouByID"), clRefSource);
                    GetCheckboxList(se.GetRef("Ser_GetSerParCri"), se.GetRefByID(id, "Ser_GetSerParCriByID"), clParticiCri);
                    GetCheckboxList(se.GetRef("Ser_GetSupCen"), se.GetRefByID(id, "Ser_GetSupCenByID"), clSupportCenter);
                    GetCheckboxList(se.GetRef("Ser_GetTarCli"), se.GetRefByID(id, "Ser_GetTarCliByID"), clTargetClient);

                }
                if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
                {
                    pnAmend.Visible = false;
                    pnView.Visible = false;
                    pnAdd.Visible = true;
                }
                if (string.IsNullOrEmpty(Request.QueryString["CID"]) && (string.IsNullOrEmpty(Request.QueryString["ID"])))
                {
                    pnAmend.Visible = false;
                    pnView.Visible = true;
                    pnAdd.Visible = false;
                    gvService.DataSource = se.Getdata();
                    gvService.DataBind();
                }
            }
        }
        void GetCheckboxList(DataTable dt1, DataTable dt2, CheckBoxList cl)
        {
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                cl.Items.Add(new ListItem(dt1.Rows[i][1].ToString(), dt1.Rows[i][0].ToString()));
            }
            //Get ID
            for (int j = 0; j < cl.Items.Count; j++)
            {
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    if (dt2.Rows[i][0].ToString().Equals(cl.Items[j].Value))
                    {
                        cl.Items[j].Selected = true;
                    }
                }
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            pnView.Visible = false;
            pnAdd.Visible = true;
            pnAmend.Visible = false;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckValidation() == "")
            {
                try
                {
                    int id = int.Parse(Request.QueryString["ID"]);
                    se.ServiceName = txtSerName.Text;
                    se.ServiceShortDes = txtShortDes.Text;
                    se.ContactID = int.Parse(hdContact.Value);
                    se.SubType = dlServiceSubType.SelectedValue;
                    se.ClientDescription = txtClientDes.Text;
                    se.ServiceAttendance = dlAttendannce.SelectedValue;
                    se.ServiceStartExpected = txtStartExp.Text;
                    se.ServiceStartDate = txtStartDate.Text;
                    se.ServiceEndDate = txtEndDate.Text;
                    se.ServiceExtendable = ckExtandable.Checked ? 1 : 0;
                    se.ServiceExtenYears = ckExtandable.Checked ? int.Parse(txtExtenYear.Text) : 0;
                    se.ServiceExtenMonth = ckExtandable.Checked ? int.Parse(txtExtenMonth.Text) : 0;
                    se.IsActive = ckActive.Checked ? 1 : 0;
                    se.ServiceFullDes = txtDesFull.Text;
                    se.DeptCode = txtDeptCode.Text;
                    se.ServiceType = dlSerType.SelectedValue;
                    se.ServiceDesDel = txtDesDelivery.Text;
                    se.ServiceContractCode = txtContactCode.Text;
                    se.ServiceContractValue = txtContactValue.Text;
                    se.ContractStagedPayment = ckStagedPayment.Checked ? 1 : 0;
                    se.ReferralProcess = dlProcessMethod.SelectedValue;
                    se.ServiceTimeLimited = ckTimeLimited.Checked ? 1 : 0;
                    se.ServiceTimeLimitedMonth = ckTimeLimited.Checked ? int.Parse(txtLimitedMonth.Text) : 0;
                    se.ServiceTimeLimitedYear = ckTimeLimited.Checked ? int.Parse(txtLimitedYear.Text) : 0;
                    se.ProgramID = int.Parse(dlProgram.SelectedValue);
                    se.ServiceID = id;
                    se.Update(se);

                    se.DelRef("Ser_DelAcc", id);
                    InsertRef("Ser_InsertAcc", clClientAcc, id);
                    se.DelRef("Ser_DelBarCri", id);
                    InsertRef("Ser_InsertBarCri", clBarriers, id);
                    se.DelRef("Ser_DelBenCri", id);
                    InsertRef("Ser_InsertBenCri", clBenefit, id);
                    se.DelRef("Ser_DelClientJourney", id);
                    InsertRef("Ser_InsertClientJourney", clClientJourrey, id);
                    se.DelRef("Ser_DelClientSupPro", id);
                    InsertRef("Ser_InsertClientSupPro", clSupportProcess, id);
                    se.DelRef("Ser_DelClientOutCome", id);
                    InsertRef("Ser_InsertClientOutCome", clClientOutCome, id);
                    se.DelRef("Ser_DelDisCri", id);
                    InsertRef("Ser_InsertDisCri", clDisability, id);
                    se.DelRef("Ser_DelEthCri", id);
                    InsertRef("Ser_InsertEthCri", clEthnic, id);
                    se.DelRef("Ser_DelIntervention", id);
                    InsertRef("Ser_InsertIntervention", clIntervention, id);
                    se.DelRef("Ser_DelOtherService", id);
                    InsertRef("Ser_InsertOtherService", clOtherService, id);
                    se.DelRef("Ser_DelSerParCri", id);
                    InsertRef("Ser_InsertOthSerParCri", clParticiCri, id);
                    se.DelRef("Ser_DelPerCirCri", id);
                    InsertRef("Ser_InsertPerCirCri", clPersonalCri, id);
                    se.DelRef("Ser_DelRefSou", id);
                    InsertRef("Ser_InsertRefSou", clRefSource, id);
                    se.DelRef("Ser_DelSupCen", id);
                    InsertRef("Ser_InsertSupCen", clSupportCenter, id);
                    se.DelRef("Ser_DelTarCli", id);
                    InsertRef("Ser_InsertTarCli", clTargetClient, id); ;
                    Label2.Text = "Update Service successfully";
                    if (dlServiceSubType.SelectedValue == "Contract")
                    {
                        try
                        {
                            ce.ServiceID = se.GetID();
                            ce.Participation = dlParticipation.SelectedValue;
                            ce.Update(ce);
                            se.DelRef("Ser_DelContractObli", id);
                            InsertRef("Ser_InsertContractObli", clContractObligation, id);
                            se.DelRef("Ser_DelContractOutCome", id);
                            InsertRef("Ser_InsertContractOutCome", clContractOutCome, id);
                            Label2.Text = "Update Service and Contract successfully";
                        }
                        catch (Exception a)
                        {
                            Label2.Text = "Error while Update Contract";
                        }
                    }
                    if (dlServiceSubType.SelectedValue == "Funding")
                    {
                        try
                        {
                            fe.FundingSource = dlFundingSource.SelectedValue;
                            fe.FunContactDetail = int.Parse(idMediaContact.Value);
                            fe.FundingAmount = txtFunAmount.Text;
                            fe.FundingStart = txtFunStart.Text;
                            fe.FundingEnd = txtFunEnd.Text;
                            fe.FunForText = txtFundaisingText.Text;
                            fe.FunWhy = txtFundaisingWhy.Text;
                            fe.FunDonorAnon = ckFundaisingDonorAnon.Checked ? 1 : 0;
                            fe.FunDonorAmount = txtFundaisingDonoAmount.Text;
                            fe.FundingNeed = txtFunNeeds.Text;
                            fe.FunConNeed = ckFunContiNeed.Checked ? 1 : 0;
                            fe.FunConAmount = txtFunContiAmount.Text;
                            fe.FunConDetail = txtFunConDetails.Text;
                            fe.FundraisingNeed = txtFundaisingNeed.Text;
                            fe.FundraisingRequiredby = txtFundaisingRequiBy.Text;
                            fe.FundraisingCompleted = ckFundaisingComplete.Checked ? 1 : 0;
                            fe.FundraisingCompletedDate = txtFundaisingCompleDate.Text;
                            fe.FundraisingDonationDate = txtFundaisingDonationDate.Text;
                            fe.FundraisingDonationIncremental = ckFundaisingDonaIncrement.Checked ? 1 : 0;
                            fe.ServiceID = se.GetID();
                            fe.Update(fe);
                            Label2.Text = "Update Service and Funding successfully";
                        }
                        catch (Exception a)
                        {
                            Label2.Text = "Error while Update Funding";
                        }
                    }

                }
                catch (Exception ax)
                {
                    Label2.Text = ax.Message;// "Error while Update Service";
                }
            }
            else
            {
                Label2.Text = CheckValidation();
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("/FormView/Service.aspx");
        }

        protected void dlServiceSubType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dlServiceSubType.SelectedIndex == 0)
            {
                lbdiv.Text = "";
            }
            if (dlServiceSubType.SelectedIndex == 1)
            {
                lbdiv.Text = "<li><a href=\"#Contract\" class=\"tab\">Contract</a></li>";
            }
            if (dlServiceSubType.SelectedIndex == 2)
            {
                lbdiv.Text = "<li><a href=\"#Funding\" class=\"tab\">Funding</a></li>";
            }
        }
        void InsertRef(string proc, CheckBoxList cl, int id)
        {
            se.ServiceID = id;
            se.Procedure = proc;
            string a = GetValueCheckBoxList(cl);
            string[] tmp = a.Split('=');
            for (int i = 0; i < tmp.Count() - 1; i++)
            {
                se.RefID = int.Parse(tmp[i]);
                se.InsertRef(se);
            }
        }
        bool CheckNum(string a)
        {
            int number;
            bool result = Int32.TryParse(a, out number);
            if (result)
            {
                return true;
            }
            else
                return false;
        }
        string GetValueCheckBoxList(CheckBoxList cl)
        {
            string lb = string.Empty;
            for (int i = 0; i < cl.Items.Count; i++)
            {
                if (cl.Items[i].Selected == true)
                {
                    lb += cl.Items[i].Value + "=";
                }
            }
            return lb;
        }
        string CheckValidation()
        {
            string err = "";
            if (txtSerName.Text == "")
            {
                err += "Input Service Name" + "</br>";
            }
            if (txtShortDes.Text == "")
            {
                err += "Input Service Short Description" + "</br>";
            }
            if (hdContact.Value == "")
            {
                err += "Select Lead Contact" + "</br>";
            }
            if (txtDeptCode.Text == "")
            {
                err += "Input Dept Code" + "</br>";
            }
            if (dlServiceSubType.SelectedValue == "Funding")
            {
                if (idMediaContact.Value == "")
                {
                    err += "Select Funding Contact Detail" + "</br>";
                }
                if (txtFunAmount.Text == "")
                {
                    err += "Input Funding Amount" + "</br>";
                }
            }
            if (ckExtandable.Checked == true)
            {
                if (CheckNum(txtExtenMonth.Text) == false || CheckNum(txtExtenYear.Text) == false)
                {
                    err += "Service Extendable Month and Year must is numberic" + "</br>";
                }
            }
            if (ckTimeLimited.Checked == true)
            {
                if (CheckNum(txtLimitedMonth.Text) == false || CheckNum(txtLimitedYear.Text) == false)
                {
                    err += "Service Time Limited Month and Year must is numberic" + "</br>";
                }
            }
            return err;
        }

        protected void btnCopy_Click(object sender, EventArgs e)
        {
            if (GetRadio(gvService) == "")
            {
                tb.Text = "Please select a Service to copy";
            }
            else
            {
                tb.Text = "";
                int id = int.Parse(GetRadio(gvService));
                Response.Redirect("/FormView/Service.aspx?CID=" + id);
            }
        }
        string GetRadio(GridView gv)
        {
            string rd = "";
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                RadioButton ck = (RadioButton)gv.Rows[i].Cells[0].FindControl("rdbauthid");
                if (ck != null)
                {
                    if (ck.Checked == true)
                    {
                        Label lb = (Label)gv.Rows[i].Cells[1].FindControl("lbID");
                        rd = lb.Text;
                    }
                }

            }
            return rd;
        }

        protected void gvPremise_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);
            sp.PreId = index;
            sp.Del_SerPre(sp);
            int ids = int.Parse(Request.QueryString["ID"]);
            sp.SerId = ids;
            gvPremise.DataSource = sp.GetServicePremise(sp);
            gvPremise.DataBind();

            //if (e.CommandName == "Remove")
            //{
                //GridViewRow gvRow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                //Label lbl_bs_id = (Label)gvPremise.FindControl("lbID");
                //Response.Write(lbl_bs_id.Text);

                //int index = Convert.ToInt32(e.CommandArgument);
                //sp.PreId = index;
                //sp.Del_SerPre(sp);
                //int ids = int.Parse(Request.QueryString["ID"]);
                //gvPremise.DataSource = sp.GetServicePremise(sp);
                //gvPremise.DataBind();
                //Label lb = (Label)GridView1.Rows[0].Cells[0].FindControl("lbID");
            //}
           
        }

        protected void gvOrg_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Role")
            {
                //int index = Convert.ToInt32(e.CommandArgument);
                mess.Text = ValueRoles.Value;
            }
        }

        protected void Select_Click(object sender, EventArgs e)
        {
            if (GetRadio(GridView1) == "")
            {
                lbtbao.Text = "Please select a Premise to copy";
            }
            else
            {
                if (txtProjectCode.Text == "")
                {
                    lbtbao.Text = "Input Project Code";
                }
                else
                {
                    lbtbao.Text = "";
                    int id = int.Parse(GetRadio(GridView1));
                    int idp = id;
                    int ids = int.Parse(Request.QueryString["ID"]);
                    sp.PreId = idp;
                    sp.SerId = ids;
                    sp.ProCode = txtProjectCode.Text;
                    sp.Insert_SerPre(sp);
                    ModalPopupExtender21.Hide();

                }
            }
        }
    }
}